from rest_framework import status
from rest_framework.decorators import action

from common.authentications import TokenAuthentication
from common.response import JsonResponse
from common.viewsets import BaseViewSet
from license import constants as c, serializers, forms, services
from license.models.license import Serial


class LicenseView(BaseViewSet):
    """
    客户端证书管理

    """
    queryset = Serial.sharding_get(1).objects.filter()
    serializer_class = serializers.SerialModelSerializer

    @action(methods=['POST'], detail=False, authentication_classes=[TokenAuthentication, ])
    def activate(self, request):
        """
        证书激活
        url: POST /license/activate/
        """
        form = forms.ActivateForm(request.data)
        if not form.is_valid():
            # 获取到错误列表中的第一个错误
            fields, error_message = next(iter(form.errors.items()), None)
            return JsonResponse(message=error_message[0], code=c.API_MESSAGE_PARAM_ERROR,
                                status=status.HTTP_400_BAD_REQUEST)
        data = form.cleaned_data
        result_dict_or_error_code, flag = services.serial_activate(
            account=request.user,
            machine_code=data['machine_code'],
            raw_machine_info=data['raw_machine_info'],
            serial_code=data['serial_code'],
            cpu_sn=data['cpu_sn'],
            memory_sn=data['memory_sn'],
            disk_sn=data['disk_sn'],
            mac=data['mac']
        )
        if not flag:
            return JsonResponse(message=c.ERROR_TABLE[result_dict_or_error_code], code=result_dict_or_error_code,
                                status=status.HTTP_400_BAD_REQUEST)
        return JsonResponse(message="激活成功", code=c.API_MESSAGE_OK, data=result_dict_or_error_code,
                            status=status.HTTP_200_OK)

    @action(methods=['POST'], detail=False)
    def generate_ts(self, request):
        """
        生成ts文件
        url: POST /license/generate_ts/
        """
        form = forms.GenerateTsForm(request.data)
        if not form.is_valid():
            fields, error_message = next(iter(form.errors.items()), None)
            return JsonResponse(message=error_message[0], code=c.API_MESSAGE_PARAM_ERROR,
                                status=status.HTTP_400_BAD_REQUEST)
        data = form.cleaned_data
        resp_or_error_code, flag = services.generate_ts(data['machine_code'])
        if not flag:
            return JsonResponse(message=c.ERROR_TABLE[resp_or_error_code], code=resp_or_error_code,
                                status=status.HTTP_400_BAD_REQUEST)
        return JsonResponse(message="ok", code=c.API_MESSAGE_OK, data=resp_or_error_code, status=status.HTTP_200_OK)

    @action(methods=['POST'], detail=False)
    def download_ts(self, request):
        """
        下载ts文件
        url: POST /license/download_ts/
        """
        form = forms.DownloadTsForm(request.data)
        if not form.is_valid():
            fields, error_message = next(iter(form.errors.items()), None)
            return JsonResponse(message=error_message[0], code=c.API_MESSAGE_PARAM_ERROR,
                                status=status.HTTP_400_BAD_REQUEST)
        data = form.cleaned_data
        result_dict_or_error_code, flag = services.download_ts(
            machine_code=data['machine_code']
        )
        if not flag:
            return JsonResponse(message=c.ERROR_TABLE[result_dict_or_error_code], code=result_dict_or_error_code,
                                status=status.HTTP_400_BAD_REQUEST)
        return JsonResponse(message="ok", data=result_dict_or_error_code, code=c.API_MESSAGE_OK,
                            status=status.HTTP_200_OK)

    @action(methods=['POST'], detail=False)
    def ts_status(self, request):
        """
        查询ts文件状态
        url: POST /license/ts_status/
        """
        form = forms.TsStatusForm(request.data)
        if not form.is_valid():
            fields, error_message = next(iter(form.errors.items()), None)
            return JsonResponse(message=error_message[0], code=c.API_MESSAGE_PARAM_ERROR,
                                status=status.HTTP_400_BAD_REQUEST)
        data = form.cleaned_data
        result_dict_or_error_code, flag = services.ts_status(
            machine_code=data['machine_code']
        )
        if not flag:
            return JsonResponse(message=c.ERROR_TABLE[result_dict_or_error_code], code=result_dict_or_error_code,
                                status=status.HTTP_400_BAD_REQUEST)
        return JsonResponse(message="ok", data=result_dict_or_error_code, code=c.API_MESSAGE_OK,
                            status=status.HTTP_200_OK)

    @action(methods=['POST'], detail=False)
    def refresh(self, request):
        """
        刷新证书有效期
        url: POST /license/refresh/
        """
        form = forms.CertRefreshForm(request.data)
        if not form.is_valid():
            print(form.errors)
            fields, error_message = next(iter(form.errors.items()), None)
            return JsonResponse(message=error_message[0], code=c.API_MESSAGE_PARAM_ERROR,
                                status=status.HTTP_400_BAD_REQUEST)
        data = form.cleaned_data
        result_dict_or_error_code, flag = services.cert_renewal(
            machine_code=data['machine_code']
        )
        if not flag:
            return JsonResponse(message=c.ERROR_TABLE[result_dict_or_error_code], code=result_dict_or_error_code,
                                status=status.HTTP_400_BAD_REQUEST)
        return JsonResponse(message="ok", data=result_dict_or_error_code, code=c.API_MESSAGE_OK,
                            status=status.HTTP_200_OK)
